import numpy as np
from PIL import Image, ImageOps
from tflite_runtime.interpreter import Interpreter

# 加载 TensorFlow Lite 模型
interpreter = Interpreter(model_path="../model/keras_model.tflite")
interpreter.allocate_tensors()

# 获取输入和输出张量的详细信息
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# 加载并预处理输入图像
image = Image.open("../apple.png").convert("RGB")
size = (224, 224)
image = ImageOps.fit(image, size, Image.Resampling.LANCZOS)

# 转换为 numpy 数组并归一化
image_array = np.asarray(image)
normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1

# 将图像数据传入模型
input_data = np.expand_dims(normalized_image_array, axis=0).astype(np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data)

# 执行推理
interpreter.invoke()

# 获取输出结果
output_data = interpreter.get_tensor(output_details[0]['index'])

# 获取预测结果
index = np.argmax(output_data)
class_names = open("../model/labels.txt", "r").readlines()
class_name = class_names[index]
confidence_score = output_data[0][index]

# 输出预测结果和置信度
print("Class:", class_name.strip())
print("Confidence Score:", confidence_score)
